#!/usr/bin/env python

# ftalat - Frequency Transition Latency Estimator
# Copyright (C) 2013 Universite de Versailles
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Script to extract results from the files generated by ftlat_runner.sh
# Then the outputted files can be rendered by the GNUPlot script

# usage :
# ./extract.py input_folder output_folder

import sys, os
import shutil
import glob

# Usual argument checking
if len(sys.argv) != 3:
   print './extract.py input_folder output_folder'
   sys.exit()
   
if not os.path.isdir(sys.argv[1]):
   print sys.argv[1] + " is not a directory"
   sys.exit()
   
if not os.path.isdir(sys.argv[2]):
   print sys.argv[2] + " is not a directory"
   sys.exit()
      
# Check turbo freq
turboFreq=0
try:
   turboFile = open(sys.argv[1] + "/turbo","r")
   turboFreq = int(turboFile.read().strip())
   turboFile.close()
except IOError:
   print "turbo file not found in " + sys.argv[1]
   sys.exit()
      
# Clean files in output folders
oldFiles = glob.glob(sys.argv[2]+"/*.csv")
if len(oldFiles) != 0:
   var = raw_input("There are some CSV files in output folder, these will be deleted [Y/n] ")

   if var == "y" or var == "Y":
      for f in oldFiles:
         os.remove(f)
   else:
      print "These files needs to be removed to not collide with the script ... aborting"
      sys.exit()
      
# Copy turbo stamp in results folder
shutil.copy2(sys.argv[1]+"/turbo",sys.argv[2]+"/turbo")

# Get the sorted files list
resultsFiles = glob.glob(sys.argv[1]+"/*.txt")
sortedResultsFiles = sorted(resultsFiles)

prevStartFreq = 0
switch = True
for f in sortedResultsFiles:
   
   # Extract the freqs from the file name
   simplifiedName, fileExtension = os.path.splitext(os.path.basename(f))
   
   freqsString = simplifiedName.split("_")[1] # At this point we have "startFreq-targetFreq"
   startFreqString , targetFreqString = freqsString.split("-")
   startFreq = int(startFreqString)
   targetFreq = int(targetFreqString)
   
   # That, can happen if turbo is handled
   if prevStartFreq != startFreq:
      if switch == False:
         outTFile = open(sys.argv[2] + "/results_{0}.csv".format(prevStartFreq),"a")
         outTFile.write("0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n")
         outTFile.close()
      switch = False
   
   prevStartFreq = startFreq   
   
   # Check if it's turbo (and in this case, we just ignore it)
   if targetFreq == turboFreq:
      continue
   
   # Open and read data
   inFile = open(f)
   dataFile = inFile.readlines()
   inFile.close()
   
   datas = []
   for line in dataFile: 
      line = line.rstrip()
      if len(line) == 0:
         continue
         
      if line.find("Change time :") != -1:
         datas.append(line.split(" ")[3])
         
   # output the results that we found
   outputFileName = sys.argv[2] + "/results_" + startFreqString + ".csv"
   outFile = open(outputFileName,"a")
   
   # Checks if the we jump the startFreq == targetFreq case
   # In such case, we want to just output 0
   if switch == False and targetFreq > startFreq:
      switch = True
      outFile.write("0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n")
   
   for data in datas:
      outFile.write(data + " ")
   outFile.write("\n")
      
   outFile.close()
   
# For the last freq, we did not output 0, let's do it
if switch == False and prevStartFreq != 0:
   outFile = open(sys.argv[2] + "/results_{0}.csv".format(prevStartFreq),"a")
   outFile.write("0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n")
   outFile.close()
